<?php


namespace App\Http\Controllers\Admin;
use App\Http\Controllers\BaseController;
use App\Jobs\DeleteAttach;
use App\Jobs\DeleteStar;
use App\Models\Category;
use App\Models\HoneyBalance;
use App\Models\Star;
use App\Models\User;
use App\Models\Work;
use App\Services\HoneyBalanceService;
use App\Services\NotifyService;
use Dingo\Api\Http\Request;

class WorkController extends BaseController
{
    public $model = Work::class;
    /**
     * 列表
     * @param Request $request
     * @return mixed
     */
    public function index(Request $request) {
        $title = $request->input('title');
        $category_id = $request->input('category_id');
        $parent_category_id = $request->input('parent_category_id');
        $order_by_key = $request->input('order_by_key', 'sort');
        $order_by_value = $request->input('order_by_value', 'desc');
        $nickname = $request->input('nickname');
        $audit_status = $request->input('audit_status', -1);
        $start_at = $request->input('start_at');
        $end_at = $request->input('end_at');

        $fields = '*';
        $list = Work::select($fields)->title($title)
            ->when($nickname, function ($q) use($nickname){
                $q->whereHas('user', function ($qt) use($nickname){
                    $qt->where('nickname', 'like', '%' . $nickname . '%');
                });
            })
            ->auditStatus($audit_status)
            ->category($category_id)
            ->startAt($start_at)
            ->endAt($end_at)
            ->withCertain('user', ['nickname', 'avatar_url', 'is_admin'])
            ->parentCategory($parent_category_id)
            ->withCertain('parent_category', ['title'])
            ->withCertain('category', ['title']);
        $list = $list->orderBy($order_by_key, $order_by_value)->orderBy("id", "desc")
            ->paginate(\request('per_page', 20));

        return $this->paginate($list);
    }

    public function info(Request $request) {
        $id = \request("id");
        if (!$id) {
            return $this->failed("参数ID不存在");
        }
        $user = $this->getUser();
        $cook = Work::userStar($user->id)
            ->withCertain('category', ['title'])
            ->withCertain('parent_category', ['title'])
            ->find($id);
        return $this->success($cook);
    }


    /**
     * 保存|修改
     * @param Request $request
     * @return mixed
     * @throws \Illuminate\Validation\ValidationException
     */
    public function store(Request $request) {
        $input = $request->input();
        $user = $this->getUser();
        $input['user_id'] = $this->getUserId();
        $id = \request("id");
        $category = Category::find($input['category_id']);
        if (!$category)
            return $this->failed('分类id不存在');
        $input['parent_category_id'] = $category->parent_id;
        if ($id) {
            $model = Work::find($id);
            if (!$model) {
                return $this->failed("id对应数据不存在");
            }
            $model->update($input);
        } else {
            $info = Work::create($input);
            $id = $info->id;
            $user->increment('work_count', 1);
        }
        return $this->success($id);
    }

    public function destroy(Request $request) {
        $this->validate($request, [
            'ids' => 'required'
        ]);
        $ids = $request->input('ids');
        $arr_id = explode(",", $ids);

        foreach ($arr_id as $id) {
            $model = $this->model::find($id);
            if ($model) {
                if ($model->audit_status == 1)
                    HoneyBalanceService::store($model->user_id, -HoneyBalance::POINT_WORK, HoneyBalance::TYPE_WORK, $model->id, true);

                $user_id = $model->user_id;
                $user = User::find($user_id);
                $image_attach = $model->image_file;
                $video_attach = $model->video_file;
                if ($user->work_count)
                    $user->increment('work_count', -1);

                if ($model->delete()){
                    dispatch(new DeleteAttach($image_attach));
                    dispatch(new DeleteAttach($video_attach));
                    $this->dispatch(new DeleteStar(Star::TYPE_Work, $id, $user_id));
                }
            }
        }
        return $this->success([]);
    }

    public function editStatus(Request $request) {
        $this->validate($request, [
            'ids' => 'required',
            'value' => 'required',
            'action' => 'required'
        ]);
        $value = \request('value');
        $action = \request('action');
        $reason = \request('reason', '');
        $ids = $request->input('ids');
        $arr_id = explode(",", $ids);

        $list = $this->model::whereIn('id', $arr_id)->get();
        $old_status = 0;
        foreach ($list as $item) {
            if ($action == 'audit') {
                $old_status = $item->audit_status;
                $item->audit_status = $value;
            } elseif ($action == 'black') {
                $item->is_black = $value;
            } elseif ($action == 'vip') {
                $item->is_vip = $value;
            } else if($action == 'sort') {
                $item->sort = $value;
            }
            if ($item->save()) {
                if (method_exists($this, '_after_editStatus')) {
                    $this->_after_editStatus($item, $action, $value, $reason, $old_status);
                }
            }
        }
        return $this->success([]);
    }

    public function _after_editStatus($item, $action, $value, $reason, $old_status) {
        if ($action == 'audit' ) {
            if ($value == 2) {
                $title = $item->title . "作品审核不通过";
                $reason = '尊敬的痕迹网用户您好，您的作品"'.$item->title.'"因"'.$reason.'"而审核不通过，请修改后再次提交审核';
                NotifyService::storeSystem($item->user_id, $title, $reason);
            } else if($value == 1) {
                //判断是否赠送
                $exists = HoneyBalance::where('entity_id', $item->id)->where('type', HoneyBalance::TYPE_WORK)->where('user_id', $item->user_id)->exists();
                if (!$exists)
                    HoneyBalanceService::store($item->user_id, HoneyBalance::POINT_WORK, HoneyBalance::TYPE_WORK, $item->id, true);
            }
        }
    }

}

